import { request, type CustomAxiosRequestConfig } from '@/utils/request'
import type { ApiResponse } from '@/types/api'

// 个人中心相关接口类型定义
export interface UserProfile {
  id: string
  username: string
  name?: string
  email: string
  phone?: string
  avatar?: string
  department?: string
  position?: string
  bio?: string
  status: string
  is_verified: boolean
  roles: string[]
  permissions: string[]
  created_at: string
  updated_at: string
  last_login?: string
  login_count: number
}

export interface UpdateProfileParams {
  username?: string
  name?: string
  email?: string
  phone?: string
  department?: string
  position?: string
  bio?: string
}

// 用户偏好设置 - 与后端字段对齐
export interface UserPreferences {
  theme?: 'light' | 'dark' | 'auto'
  language?: 'zh-CN' | 'en-US' | 'ja-JP'
  timezone?: string
}

export interface ChangePasswordParams {
  current_password: string
  new_password: string
}

export interface NotificationSettings {
  email_task_assigned: boolean
  email_task_completed: boolean
  email_project_update: boolean
  email_deadline_reminder: boolean
  system_task_assigned: boolean
  system_task_completed: boolean
  system_project_update: boolean
  system_deadline_reminder: boolean
}

export interface ActivityLog {
  id: string
  user_id?: string
  user_name?: string
  action: string
  target_type: string
  target_id: string
  target_name: string
  description: string
  ip_address?: string
  user_agent?: string
  metadata?: Record<string, any>
  created_at: string
}

export interface LoginLog {
  id: string
  user_id?: string
  ip_address: string
  user_agent: string
  device_info?: string
  location?: string
  success: boolean
  login_time: string
}

export interface UserStats {
  total_projects: number
  active_projects: number
  completed_projects: number
  total_tasks: number
  completed_tasks: number
  pending_tasks: number
  overdue_tasks: number
  total_hours: number
  this_month_hours: number
}

export interface DashboardStats {
  projects: {
    total: number
    active: number
    completed: number
    overdue: number
  }
  tasks: {
    total: number
    completed: number
    pending: number
    overdue: number
  }
  work_hours: {
    today: number
    this_week: number
    this_month: number
    total: number
  }
  recent_activities: ActivityLog[]
}

// 获取当前用户信息
export const getCurrentUserProfile = async (): Promise<UserProfile> => {
  const response = await request.get<ApiResponse<UserProfile>>('/profile/me', {
    showLoading: true,
    showError: true
  } as CustomAxiosRequestConfig)
  if (!response.data.data) {
    throw new Error('用户数据不存在')
  }
  return response.data.data // 后端返回的是ApiResponse<UserProfile>格式
}

// 更新当前用户资料
export const updateCurrentUserProfile = async (data: UpdateProfileParams): Promise<UserProfile> => {
  const response = await request.put<ApiResponse<UserProfile>>('/profile/me', data, {
    showLoading: true,
    loadingText: '保存中...',
    showError: true,
    showSuccess: false // 由组件控制成功消息显示，避免重复提示
  } as CustomAxiosRequestConfig)
  if (!response.data.data) {
    throw new Error('用户数据不存在')
  }
  return response.data.data // 后端返回的是ApiResponse<UserProfile>格式
}

// 获取用户头像上传URL
export const getUserAvatarUploadUrl = () => {
  return request.get<ApiResponse<{
    upload_url: string
    max_size: number
    allowed_types: string[]
  }>>('/profile/avatar/upload-url', {
    showLoading: false,
    showError: true
  } as CustomAxiosRequestConfig).then(response => response.data)
}

// 上传用户头像
export const uploadUserAvatar = (file: File) => {
  const formData = new FormData()
  // 后端期望的字段名是 'file'，不是 'avatar'
  formData.append('file', file)
  
  return request.post<ApiResponse<{ avatar: string }>>('/profile/avatar', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    showLoading: true,
    loadingText: '上传中...',
    showError: true,
    showSuccess: false // 由组件控制成功消息显示，避免重复提示
  } as CustomAxiosRequestConfig).then(response => response.data)
}

// 修改密码
export const changeUserPassword = (data: ChangePasswordParams) => {
  return request.post<ApiResponse<null>>('/profile/change-password', data, {
    showLoading: true,
    loadingText: '修改中...',
    showError: true,
    showSuccess: true
  } as CustomAxiosRequestConfig).then(response => response.data)
}

// 验证密码
export const verifyUserPassword = (password: string) => {
  return request.post<ApiResponse<null>>('/profile/verify-password', { password }, {
    showLoading: true,
    loadingText: '验证中...',
    showError: true
  } as CustomAxiosRequestConfig).then(response => response.data)
}

// 获取通知设置
export const getNotificationSettings = () => {
  return request.get<ApiResponse<NotificationSettings>>('/profile/notifications', {
    showLoading: false,
    showError: true
  } as CustomAxiosRequestConfig).then(response => response.data)
}

// 更新通知设置
export const updateNotificationSettings = (data: NotificationSettings) => {
  return request.put<ApiResponse<NotificationSettings>>('/profile/notifications', data, {
    showLoading: true,
    loadingText: '保存中...',
    showError: true,
    showSuccess: true
  } as CustomAxiosRequestConfig).then(response => response.data)
}

// 活动记录列表响应类型
export interface ActivityLogListResponse {
  data: ActivityLog[]
  total: number
  page: number
  limit: number
}

// 获取用户活动记录
export const getUserActivityLogs = (params?: {
  page?: number
  limit?: number
  action?: string
  target_type?: string
  start_date?: string
  end_date?: string
}): Promise<ApiResponse<ActivityLogListResponse>> => {
  return request.get<ApiResponse<ActivityLogListResponse>>('/profile/activities', {
    params,
    showLoading: false,
    showError: true
  } as CustomAxiosRequestConfig).then(response => response.data)
}

// 获取用户登录日志
export const getUserLoginLogs = (params?: {
  page?: number
  limit?: number
  start_date?: string
  end_date?: string
}) => {
  return request.get<ApiResponse<{
    data: LoginLog[]
    total: number
    page: number
    limit: number
  }>>('/profile/login-logs', {
    params,
    showLoading: false,
    showError: true
  } as CustomAxiosRequestConfig).then(response => response.data)
}

// 获取用户统计数据
export const getUserStatistics = () => {
  return request.get<ApiResponse<UserStats>>('/profile/stats', {
    showLoading: false,
    showError: true
  } as CustomAxiosRequestConfig).then(response => response.data)
}

// 获取仪表盘统计数据
export const getDashboardStatistics = () => {
  return request.get<ApiResponse<DashboardStats>>('/profile/dashboard-stats', {
    showLoading: false,
    showError: true
  } as CustomAxiosRequestConfig).then(response => response.data)
}

// 获取用户偏好设置
export const getUserPreferences = async (): Promise<ApiResponse<UserPreferences>> => {
  try {
    const response = await request.get<ApiResponse<UserPreferences>>('/profile/preferences', {
      showLoading: false,
      showError: false // 如果接口不存在，不显示错误
    } as CustomAxiosRequestConfig)
    
    // 确保返回统一格式
    if (response.data && response.data.success && response.data.data) {
      return response.data
    } else if (response.data && response.data.data) {
      // 兼容直接返回data的情况
      return {
        success: true,
        data: response.data.data,
        message: '获取用户偏好设置成功'
      }
    }
    
    // 如果没有数据，返回默认值
    return {
      success: true,
      data: { theme: 'light', language: 'zh-CN', timezone: 'Asia/Shanghai' },
      message: '获取用户偏好设置成功'
    }
  } catch (error) {
    // 如果接口不存在或失败，返回默认值
    console.log('获取用户偏好设置失败，使用默认值:', error)
    return {
      success: true,
      data: { theme: 'light', language: 'zh-CN', timezone: 'Asia/Shanghai' },
      message: '使用默认偏好设置'
    }
  }
}

// 更新用户偏好设置
export const updateUserPreferences = async (data: UserPreferences): Promise<ApiResponse<UserPreferences>> => {
  try {
    const response = await request.put<ApiResponse<UserPreferences>>('/profile/preferences', data, {
      showLoading: true,
      loadingText: '保存中...',
      showError: true,
      showSuccess: false // 由组件控制成功消息显示
    } as CustomAxiosRequestConfig)
    
    // 确保返回统一格式
    if (response.data && response.data.success && response.data.data) {
      // 同时更新localStorage以保持同步
      if (data.theme) {
        localStorage.setItem('theme', data.theme)
      }
      return response.data
    } else if (response.data && response.data.data) {
      // 兼容直接返回data的情况
      if (data.theme) {
        localStorage.setItem('theme', data.theme)
      }
      return {
        success: true,
        data: response.data.data,
        message: '用户偏好设置更新成功'
      }
    }
    
    throw new Error('更新用户偏好设置失败：响应数据格式错误')
  } catch (error: any) {
    // 如果接口不存在或失败，尝试保存到localStorage作为降级方案
    if (data.theme) {
      localStorage.setItem('theme', data.theme)
      console.warn('后端接口不可用，已保存到localStorage:', data.theme)
    }
    throw error
  }
}